package com.shaoshaohuo.app.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.liam.imageload.LoadUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.FileType;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BaseUserInfo;
import com.shaoshaohuo.app.entity.UploadImageEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.log.LogUtil;
import com.shaoshaohuo.app.net.HttpRequest;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.utils.AreaUtil;
import com.shaoshaohuo.app.utils.CameraUtil;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;

import org.hybridsquad.android.library.CropHandler;
import org.hybridsquad.android.library.CropHelper;
import org.hybridsquad.android.library.CropParams;

/**
 * 个人资料
 * by cao
 */
public class MyInfoActivity extends BaseActivity implements OnClickListener, CropHandler {
    private static final String LOG_TAG = "MyInfoActivity";
    private boolean isEditState = false;//是否处于编辑状态


    //审核状态 0：未认证；1待审核，2审核失败，3审核通过
    private static final int AUDIT_STATUS_UMCOMMIT = 0; //未认证
    private static final int AUDIT_STATUS_WAIT_AUDIT = 1;  //待审核
    private static final int AUDIT_STATUS_FAILURE = 2;  //审核失败
    private static final int AUDIT_STATUS_SUCCESS = 3;  //审核通过

    private TopbarView mTopbarView;

    private LinearLayout ll_head;
    private ImageView iv_head;
    private LinearLayout ll_name;
    private EditText et_name;
    private LinearLayout ll_sex;
    private EditText et_sex;
    private LinearLayout ll_address;
    private EditText et_address;
    private LinearLayout ll_name_register;
    private LinearLayout ll_car_register;


    CropParams mCropParams = new CropParams();
    private String mHeadViewUri;
    private String mHeadViewUrl;

    private CascadingMenuPopWindow cascadingMenuPopWindow;
    private Area city;
    private TextView tvUserAuditStatus;
    private TextView tvCarAuditStatus;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        initView();
        setUpView();
//        requestData();
    }

    /**
     * 访问远程
     */
    private void requestData() {
        RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new HttpRequest.RequestListener() {
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData != null && resultData.isOk()) {
                    UserInfoEntity userEntity = (UserInfoEntity) resultData;
                    updateUI(userEntity);
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {

            }
        });
    }

    private void updateUI(UserInfoEntity userEntity) {
        UserInfoEntity.UserInfo user = userEntity.getData();
        BaseUserInfo userInfo = user.getBaseinfo();
        if (userInfo != null) {
            mHeadViewUrl = userInfo.getAvatar();
            ImageLoader.getInstance().displayImage(userInfo.getAvatar(), iv_head,
                    ImageLoadUtil.getDisplayImageOptions(R.drawable.pic_head_ad, 180));

            et_name.setText(userInfo.getRealname());

            String gender = userInfo.getGender();
            LogUtil.i(LOG_TAG, "user gender: " + gender);
            if (!TextUtils.isEmpty(gender)) {
                switch (gender) {
                    case "1":
                        et_sex.setText("男");
                        break;
                    case "2":
                        et_sex.setText("女");
                        break;
                }
            }

            Integer addressCityId = userInfo.getAddressCityId();
            if (addressCityId != null) {
                et_address.setText(AreaUtil.getAreaFullname(String.valueOf(addressCityId)));
            }

            checkAuthState(user);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    private void initView() {
        mTopbarView = (TopbarView) findViewById(R.id.topbar);

        ll_head = (LinearLayout) findViewById(R.id.ll_head);
        iv_head = (ImageView) findViewById(R.id.iv_head);
        ll_name = (LinearLayout) findViewById(R.id.ll_name);
        et_name = (EditText) findViewById(R.id.et_name);
        ll_sex = (LinearLayout) findViewById(R.id.ll_sex);
        et_sex = (EditText) findViewById(R.id.et_sex);
        ll_address = (LinearLayout) findViewById(R.id.ll_address);
        et_address = (EditText) findViewById(R.id.et_address);

        ll_name_register = (LinearLayout) findViewById(R.id.ll_name_register);
        tvUserAuditStatus = (TextView) findViewById(R.id.tv_user_audit_status);

        ll_car_register = (LinearLayout) findViewById(R.id.ll_car_register);
        tvCarAuditStatus = (TextView) findViewById(R.id.tv_car_audit_status);
    }

    private void setUpView() {
        mTopbarView.setCenterText("个人资料");
        mTopbarView.setLeftView(true, true);
        mTopbarView.setRightText("编辑");
        mTopbarView.setRightClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditState) {
                    if (TextUtils.isEmpty(mHeadViewUri)) {
                        saveInfo();
                    } else {
                        uploadFile();
                    }

                    isEditState = false;
                    mTopbarView.setRightText("编辑");
                } else {
                    isEditState = true;
                    et_name.setEnabled(true);
                    mTopbarView.setRightText("完成");
                }
            }
        });

        ll_head.setOnClickListener(this);
        ll_name.setOnClickListener(this);
        ll_sex.setOnClickListener(this);
        ll_address.setOnClickListener(this);
        ll_name_register.setOnClickListener(this);
        ll_car_register.setOnClickListener(this);

        et_name.setEnabled(false);
        et_sex.setEnabled(false);
        et_address.setEnabled(false);


        /*BaseUserInfo userInfo = AccountManager.getUserInfo();
        if (userInfo != null) {
            mHeadViewUrl = userInfo.getAvatar();
            ImageLoader.getInstance().displayImage(userInfo.getAvatar(), iv_head,
                    ImageLoadUtil.getDisplayImageOptions(R.drawable.pic_head_ad, 180));

            et_name.setText(userInfo.getRealname());

            String gender = userInfo.getGender();
            LogUtil.i(LOG_TAG, "user gender: " + gender);
            if (!TextUtils.isEmpty(gender)) {
                switch (gender) {
                    case "1":
                        et_sex.setText("男");
                        break;
                    case "2":
                        et_sex.setText("女");
                        break;
                }
            }


            et_address.setText(AccountManager.getAddress());


        }*/

    }

    // 保存 信息
    private void saveInfo() {
        String name = et_name.getText().toString();
        String num = AccountManager.getUserInfo().getIdnum();
        String gender = null;
        String sex = et_sex.getText().toString();
        if ("男".equals(sex)) {
            gender = "1";
        } else if ("女".equals(sex)) {
            gender = "2";
        }

        if (StringUtil.isEmpty(name)) {
            showToast("姓名不能为空");
            return;
        }
        if (StringUtil.isEmpty(sex)) {
            showToast("性别不能为空");
            return;
        }

        if (city == null) {
            showToast("所在地不能为空");
            return;
        }

        startLoadingDialog();
//        LogUtil.i(LOG_TAG, "city id : " + city.getAreaId());
//        RequestService.getInstance().saveMyBaseInfo(this, mHeadViewUrl, name, num, gender, null,
//                null, null, city.getAreaId() + "", BaseEntity.class, new HttpRequest.RequestListener() {
//
//                    @Override
//                    public void onSuccess(int requestCode, BaseEntity resultData) {
//                        dismissLoadingDialog();
//                        if (resultData.isOk()) {
//                            showToast("保存成功");
//                            AccountManager.updateUserInfo(MyInfoActivity.this);
//                        } else {
//                            showToast(resultData.getMsg());
//                        }
//                    }
//
//                    @Override
//                    public void onFailed(int requestCode, Exception error, String msg) {
//                        dismissLoadingDialog();
//                        showToast(msg);
//                    }
//                });
    }

    // 上传 头像
    private void uploadFile() {

        startLoadingDialog();
        RequestService.getInstance().uploadImage(this, mHeadViewUri, FileType.IMAGE, UploadImageEntity.class, new HttpRequest.RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    UploadImageEntity entity = (UploadImageEntity) resultData;
                    mHeadViewUrl = entity.getData().getFile();
                    saveInfo();
                } else {
                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
            }
        });
    }


    private void checkAuthState(UserInfoEntity.UserInfo userInfo) {
//        String userAuthCode = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.USER_IS_AUTH, "");
//        String carAuthCode = SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.CAR_IS_AUTH, "");
        String userAuthCode = userInfo.getVerifystatus();
        String carAuthCode = userInfo.getCarinfo().getVerifystatus();
        switch (userAuthCode) {
            case "1":
                changeAuditStatus(tvUserAuditStatus, AUDIT_STATUS_WAIT_AUDIT);
                break;
            case "2":
                changeAuditStatus(tvUserAuditStatus, AUDIT_STATUS_FAILURE);
                break;
            case "3":
                changeAuditStatus(tvUserAuditStatus, AUDIT_STATUS_SUCCESS);
                break;
            default:
                changeAuditStatus(tvUserAuditStatus, AUDIT_STATUS_UMCOMMIT);
                break;
        }
        switch (carAuthCode) {
            case "1":
                changeAuditStatus(tvCarAuditStatus, AUDIT_STATUS_WAIT_AUDIT);
                break;
            case "2":
                changeAuditStatus(tvCarAuditStatus, AUDIT_STATUS_FAILURE);
                break;
            case "3":
                changeAuditStatus(tvCarAuditStatus, AUDIT_STATUS_SUCCESS);
                break;
            default:
                changeAuditStatus(tvCarAuditStatus, AUDIT_STATUS_UMCOMMIT);
                break;
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.ll_head:
                if (!isEditState) return;
                selectImage();
                break;
            case R.id.ll_name:
                if (!isEditState) return;
                et_name.setFocusable(true);
                break;
            case R.id.ll_sex:
                if (!isEditState) return;
                selectSex();
                break;
            case R.id.ll_address:
                if (!isEditState) return;
                selectAddress();
                break;
            case R.id.ll_name_register:
                //  实名认证
                Intent in = new Intent(this, AuthNameActivity.class);
                String username = et_name.getText().toString();
                if (!StringUtil.isEmpty(username)) {
                    in.putExtra(AuthNameActivity.EXTRAS_USERNAME, username);
                }
                startActivity(in);
                break;
            case R.id.ll_car_register:
                //车辆认证
                startActivity(new Intent(this, AuthCarActivity.class));
                break;
        }
    }

    //选择地址
    private void selectAddress() {
        if (cascadingMenuPopWindow == null) {
            //向三级menu添加地区数据
            cascadingMenuPopWindow = new CascadingMenuPopWindow(this, false);
            cascadingMenuPopWindow
                    .setMenuViewOnSelectListener(new CascadingMenuViewOnSelectListener() {
                        @Override
                        public void getValue(Area area, String fullname) {
                            city = area;
//                            et_address.setText(AreaUtil.getAreaFullname("" + area.getAreaId()));
                        }
                    });
            cascadingMenuPopWindow.showAsDropDown(et_address, 5, 5);
        } else if (cascadingMenuPopWindow != null
                && cascadingMenuPopWindow.isShowing()) {
            cascadingMenuPopWindow.dismiss();
        } else {
            cascadingMenuPopWindow.showAsDropDown(et_address, 5, 5);
        }
    }

    //选择性别
    private void selectSex() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(new String[]{"男", "女"}, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        et_sex.setText("男");
                        break;
                    case 1:
                        et_sex.setText("女");
                        break;
                }
            }
        });
        builder.create().show();
    }

    // 选择照片
    private void selectImage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setItems(new String[]{"相机", "相册"}, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        CameraUtil.capture(MyInfoActivity.this);
                        break;
                    case 1:
                        CameraUtil.photo(MyInfoActivity.this);
                        break;
                }
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CameraUtil.handleResult(this, requestCode, resultCode, data);
    }

    @Override
    public CropParams getCropParams() {
        return mCropParams;
    }

    @Override
    public void onPhotoCropped(Uri u) {
        String uri = u.getPath();
        LoadUtils.getInstance().loadImage(iv_head, "file://" + uri, 0, 100);
        mHeadViewUri = uri;
    }

    @Override
    public void onCropCancel() {
    }

    @Override
    public void onCropFailed(String message) {
        Toast.makeText(this, "Crop failed:" + message, Toast.LENGTH_LONG).show();
    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    protected void onDestroy() {
        if (getCropParams() != null)
            CropHelper.clearCachedCropFile(getCropParams().uri);
        super.onDestroy();
    }

    /**
     * 更改审核状态
     *
     * @param tv
     * @param status 0：未认证；1待审核，2审核失败，3审核通过
     */
    public void changeAuditStatus(TextView tv, int status) {
        if (tv == null) return;
        switch (status) {
            case AUDIT_STATUS_UMCOMMIT:
                tv.setTextColor(getResources().getColor(R.color.color_FF6368));
                tv.setText("未认证");
                break;
            case AUDIT_STATUS_WAIT_AUDIT:
                tv.setTextColor(getResources().getColor(R.color.color_FF8D3A));
                tv.setText("审核中");
                break;
            case AUDIT_STATUS_FAILURE:
                tv.setTextColor(getResources().getColor(R.color.color_FF6368));
                tv.setText("审核失败");
                break;
            case AUDIT_STATUS_SUCCESS:
                tv.setTextColor(getResources().getColor(R.color.color_77C755));
                tv.setText("已认证");
                break;
        }
    }
}
